package com.example.hu.UI;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.csht.facelib.callback.CameraDataCallback;
import com.csht.facelib.callback.FaceCallBack;
import com.csht.facelib.camera.AutoTexturePreviewView;
import com.csht.facelib.camera.CameraPreviewManager;
import com.csht.facelib.db.User;
import com.csht.facelib.manager.CshtCompareUtil;
import com.csht.facelib.manager.FaceManager;
import com.csht.facelib.utils.SpUtils;
import com.csht.facelib.view.FaceOverlayViews;
import com.example.hu.Appliction.MyApp;
import com.example.hu.R;
import com.example.hu.Utils.Contants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import androidx.appcompat.app.AlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FaceSearchActivity extends BaseActivity {

    private ImageView iv_pic;
    private TextView tv_name,tv_time,tv_msg;
    private SimpleDateFormat sdf;
    private FaceOverlayViews mFaceView;
    private  static  final   String  OutRubbishInBox_API=Contants.OutRubbishInBox_API;
    OkHttpClient okHttpClient = new OkHttpClient();
    private   String  username,carcode;
    private    static   final   String    transportId="广东省人民医院处置公司";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_search);

        init();
        initCamera();
    }

    private void init() {
        iv_pic = findViewById(R.id.iv_pic);
        tv_name = findViewById(R.id.tv_name);
        tv_time = findViewById(R.id.tv_time);
        tv_msg = findViewById(R.id.tv_msg);
        mFaceView = findViewById(R.id.draw_detect_face_view);
        mFaceView.setMirror(SpUtils.isOpenMirror());
        mFaceView.setMoveLeftOrRight(SpUtils.getMoveLeftOrRight());
        mFaceView.setMoveUpOrDown(SpUtils.getMoveUpOrDown());
        mFaceView.setScale(SpUtils.getFaceScale());

        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Intent intent = getIntent();
      carcode = intent.getStringExtra("Ufhdata");
        Log.i("carcode", carcode);
    }

    private void initCamera() {
        CshtCompareUtil.getInstance().initDatabases();
        FaceManager.getInstance().initFaceTrackSdk();
        FaceManager.getInstance().setFaceView(mFaceView);
        CameraPreviewManager.getInstance().setCameraFacing(CameraPreviewManager.CAMERA_FACING_FRONT);
        CameraPreviewManager.getInstance().startPreview((AutoTexturePreviewView)findViewById(R.id.auto_camera_preview_view), SpUtils.getCameraWidth(), SpUtils.getCameraHeight(), new CameraDataCallback() {
            @Override
            public void onGetCameraData(byte[] data, Camera camera, int width, int height) {
                FaceManager.getInstance().onDetectCheck(data, width, height, new FaceCallBack() {
                    @Override
                    public void onFaceDetectCallback(final User user) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (user != null){
                                    tv_msg.setText("验证成功");
                                    iv_pic.setImageBitmap(BitmapFactory.decodeFile(user.getIdPhoto()));
                                    tv_name.setText(user.getName());
                                    tv_time.setText(sdf.format(System.currentTimeMillis()));
                                    username=user.getName();
                                    showProgressDialog();
                                    OutRubbishInBox_Rquest(carcode,username);

                                } else {
                                    tv_msg.setText("验证失败");
                                    iv_pic.setImageResource(R.mipmap.ic_launcher);
                                    tv_name.setText("姓名");
                                    tv_time.setText("时间");
                                }
                            }
                        });
                    }

                    @Override
                    public void onTip(int code, final String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_msg.setText(msg);
                                iv_pic.setImageResource(R.mipmap.ic_launcher);
                                tv_name.setText("姓名");
                                tv_time.setText("时间");
                            }
                        });
                    }
                });
            }

            @Override
            public void onCameraParams(int width, int height) {
                mFaceView.setPreviewWidth(width);
            }
        });
    }
    private void OutRubbishInBox_Rquest(String stylecode, String username) {
        RequestBody formBody = new FormBody.Builder()
                .add("id",MyApp.getApp().getToken())
                .add("transportId",transportId)
                .add("driverName",username)
                .add("carNo",stylecode)
                .build();
        Request request = new Request.Builder()
                .url(OutRubbishInBox_API)
                .post(formBody)
                .build();
        Log.d("OutRubbishInBox_API",OutRubbishInBox_API+"?id="+MyApp.getApp().getToken()+"&driverName="+username+"&carNo="+stylecode+"&transportId="+transportId);
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }				});				//此处会发生异常//
                    }		}).start();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String  res=response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OnKeyResPonse(res);
                    }
                });
            }
        });

    }

    private void OnKeyResPonse(String res) {
        try {
            JSONObject onkeyobject = new JSONObject(res);
            String onkeyobjectString = onkeyobject.getString("message");
            if (onkeyobjectString.equals("20004")) {
                dismissProgressDialog();
                showShortToast("出库异常");
                finish();
            } else if (onkeyobjectString.equals("20005")) {
                dismissProgressDialog();
                showShortToast("出库成功");
                finish();
            } else if (onkeyobjectString.equals("20007")) {
                dismissProgressDialog();
                showShortToast("查询不到废弃物信息");
                finish();
            }else if (onkeyobjectString.equals("20017")) {
                dismissProgressDialog();
                showShortToast("查询不到废弃物信息");


                        //要执行的操作
                        finish();

            }else if (onkeyobjectString.equals("没有未出库医废")){
                dismissProgressDialog();
                showShortToast("没有未出库医废");
                finish();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        CameraPreviewManager.getInstance().stopPreview();
    }
}
